# -*- coding: utf-8 -*-

#copy py2exe sample

####################################################
#py2exe help
#D:\projects\pystore>python setup.py py2exe --help
####################################################
#Global options:
#  --verbose (-v)  run verbosely (default)
#  --quiet (-q)    run quietly (turns verbosity off)
#  --dry-run (-n)  don't actually do anything
#  --help (-h)     show detailed help message
#
#Options for 'py2exe' command:
#  --optimize (-O)       optimization level: -O1 for "python -O", -O2 for
#                        "python -OO", and -O0 to disable [default: -O0]
#  --dist-dir (-d)       directory to put final built distributions in (default
#                        is dist)
#  --excludes (-e)       comma-separated list of modules to exclude
#  --dll-excludes        comma-separated list of DLLs to exclude
#  --ignores             comma-separated list of modules to ignore if they are
#                        not found
#  --includes (-i)       comma-separated list of modules to include
#  --packages (-p)       comma-separated list of packages to include
#  --compressed (-c)     create a compressed zipfile
#  --xref (-x)           create and show a module cross reference
#  --bundle-files (-b)   bundle dlls in the zipfile or the exe. Valid levels
#                        are 1, 2, or 3 (default)
#  --skip-archive        do not place Python bytecode files in an archive, put
#                        them directly in the file system
#  --ascii (-a)          do not automatically include encodings and codecs
#  --custom-boot-script  Python file that will be run when setting up the
#                        runtime environment
#
#usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
#   or: setup.py --help [cmd1 cmd2 ...]
#   or: setup.py --help-commands
#   or: setup.py cmd --help

import distutils
import distutils.core 
import sys
import os
import fnmatch

import py2exe

# If run without args, build executables, in quiet mode.
if len(sys.argv) == 1:
    sys.argv.append("py2exe")
    #sys.argv.append("-q")

class Target:
    def __init__(self, **kw):
        self.__dict__.update(kw)
        # for the versioninfo resources
        self.version = "0.1.2006.08.07"
        self.company_name = "huihoo"
        self.copyright = "copy what?"
        self.name = "pystore"

manifest_template = '''
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
    version="5.0.0.0"
    processorArchitecture="x86"
    name="%(prog)s"
    type="win32"
/>
<description>%(prog)s Program</description>
<dependency>
    <dependentAssembly>
        <assemblyIdentity
            type="win32"
            name="Microsoft.Windows.Common-Controls"
            version="6.0.0.0"
            processorArchitecture="X86"
            publicKeyToken="6595b64144ccf1df"
            language="*"
        />
    </dependentAssembly>
</dependency>
</assembly>
'''


################################################################
RT_MANIFEST = 24
target_ui = Target(
    # used for the versioninfo resource
    description = "store file in gmail",

    # what to build
    script = "main.py",
    other_resources = [(RT_MANIFEST, 1, manifest_template % dict(prog="pystore"))],
    icon_resources = [(1, r"resource\tool\pystore.ico")],
    dest_base = "pystore")

target_ui_mockMailClient = Target(
    # used for the versioninfo resource
    description = "store file in gmail",

    # what to build
    script = "ui_diskMailBox.py",
    other_resources = [(RT_MANIFEST, 1, manifest_template % dict(prog="pystore_mockMailClient"))],
    icon_resources = [(1, r"resource\tool\pystore.ico")],
    dest_base = "pystore_mockMailClient")

 
# pywin32 COM pulls in a lot of stuff which we don't want or need.
excludes = ["pywin", "pywin.debugger", "pywin.debugger.dbgcon",
            "pywin.dialogs", "pywin.dialogs.list", "win32com.server"]

options = {
           #"compressed": 0,
           #"optimize": 2,
           "dist_dir": r"build\dist", #command line :dist-dir  , python script:dist_dir
           "ascii": 1,
           "excludes": excludes,
           "bundle_files":1, # create singlefile exe
           "dll_excludes": ["w9xpopen.exe"], # we don't need this
           "packages": ["encodings"]}

distutils.core.setup(
    #cmdclass = {'py2exe': Py2exe},
    options = {"py2exe": options},
    zipfile = None, 
    windows = [target_ui],#[target_ui,target_ui_mockMailClient],
    #data_files=[("resource", ["resource\\tool\\pystore.ico"])],# how to use it copy dir?
    )


def xcopy(source,target,exceptPatterns):
    """
    str source: copy路径
    str target: 目标路径
    str exceptPatterns:可以使用文件名模式: "*" ,  "a*.bat"...
    """
    source=os.path.normpath(source)
    target=os.path.normpath(target)
    def walk(path):
        for exceptPattern in exceptPatterns:
            if fnmatch.fnmatch(path, exceptPattern):
                return 
        if os.path.isfile( path ):
            targetFile=path.replace(source,target,1)
            targetDir=os.path.split(targetFile)[0]
            if not os.path.exists(targetDir):
                os.makedirs(targetDir)
            #shutil.copy(path, targetDir) 
            import distutils.file_util
            distutils.file_util.copy_file(path,targetDir)
        elif os.path.isdir( path ):
            for childName in os.listdir( path ):
                fullpath = os.path.normpath(os.path.join(path,childName))
                walk(fullpath)
    walk(source)

#copy all image resource  , todo del .svn files 
#distutils.dir_util.copy_tree("resource",r"build\dist\resource",preserve_mode=False)
xcopy("resource",r"build\dist\resource",exceptPatterns=["*.svn*","*Thumbs.db"])
xcopy("locale",r"build\dist\locale",exceptPatterns=["*.svn*","*Thumbs.db"])
